package org.bjf.utils;

import com.fasterxml.jackson.annotation.JsonTypeName;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author bjf
 */
@JsonTypeName
public class BgExcelReader {
    private Workbook wb;
    private Sheet sheet;
    private static BgExcelReader reader;

    private BgExcelReader() {
    }

    public static BgExcelReader getInstance() {
        reader = new BgExcelReader();
        return reader;
    }

    public BgExcelReader readByInputstream(InputStream in) {
        try {
            wb = new XSSFWorkbook(in);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return reader;
    }

    /**
     * @param startRowIndex 数据起始行
     * @param startColIndex 数据开始列
     * @param endColIndex   数据结束列
     */
    public List<List<String>> read(int startRowIndex, int startColIndex, int endColIndex) {
        List<List<String>> datas = new ArrayList<>();
        sheet = wb.getSheetAt(0);
        int lastRowNum = sheet.getLastRowNum();
        for (int i = startRowIndex; i <= lastRowNum; i++) {
            Row row = sheet.getRow(i);
            if (row == null) {
                continue;
            }
            List<String> rowData = new ArrayList<>();
            for (int j = startColIndex; j <= endColIndex; j++) {
                Cell cell = row.getCell(j);
                rowData.add(cellValueToString(cell));
            }
            datas.add(rowData);
        }
        return datas;
    }

    private static String cellValueToString(Cell cell) {
        if (cell == null) {
            return null;
        }
        String content = null;
        switch (cell.getCellType()) {
            case NUMERIC:
                Double doubleValue = cell.getNumericCellValue();
                // 格式化科学计数法，取一位整数
                //DecimalFormat df = new DecimalFormat("0");
                //content = df.format(doubleValue);
                content = doubleValue.toString();
                break;
            case STRING:
                content = cell.getStringCellValue();
                break;
            case BOOLEAN:
                Boolean booleanValue = cell.getBooleanCellValue();
                content = booleanValue.toString();
                break;
            case BLANK:
                // 空值
                break;
            case FORMULA:
                // 公式
                content = cell.getCellFormula();
                break;
            case ERROR:
                break;
            default:
                break;
        }
        return content;

    }
}